<?php
/* SVN FILE: $Id: app_model.php 847 2010-04-02 06:56:53Z jayashree_028ac09 $ */
/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
 * @package       cake
 * @subpackage    cake.app
 * @since         CakePHP(tm) v 0.2.9
 * @version       $Revision: 7847 $
 * @modifiedby    $LastChangedBy: renan.saddam $
 * @lastmodified  $Date: 2008-11-08 08:24:07 +0530 (Sat, 08 Nov 2008) $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       cake
 * @subpackage    cake.app
 */
class AppModel extends Model
{
    public $actsAs = array(
        'Containable',
		'Affiliate'
    );
    function beforeSave()
    {
        $this->useDbConfig = 'master';
        return true;
    }
    function afterSave()
    {
        $this->useDbConfig = 'default';
        return true;
    }
    function beforeDelete()
    {
        $this->useDbConfig = 'master';
        return true;
    }
    function afterDelete()
    {
        $this->useDbConfig = 'default';
        return true;
    }
	function toSaveIp()
    {
        App::import('Model', 'Ip');
        $this->Ip = new Ip();
        $this->data['Ip']['ip'] = RequestHandlerComponent::getClientIP();
        $ip = $this->Ip->find('first', array(
            'conditions' => array(
                'Ip.ip' => $this->data['Ip']['ip']
            ) ,
            'fields' => array(
                'Ip.id'
            ) ,
            'recursive' => -1,
			'limit' => 1
        ));
        if (empty($ip)) {
		    if(!empty($this->data['Ip']['ip']))
			{
            	$this->data['Ip']['host'] = gethostbyaddr($this->data['Ip']['ip']);
			}
			else
			{
				$this->data['Ip']['host'] = "";
			}
            if (!empty($_COOKIE['_geo'])) {
                $_geo = explode('|', urldecode($_COOKIE['_geo']));
                $country = $this->Ip->Country->find('first', array(
                    'conditions' => array(
                        'Country.iso2' => $_geo[0]
                    ) ,
                    'fields' => array(
                        'Country.id'
                    ) ,
                    'recursive' => -1
                ));
                if (empty($country)) {
                    $this->data['Ip']['country_id'] = 0;
                } else {
                    $this->data['Ip']['country_id'] = $country['Country']['id'];
                }
                $state = $this->Ip->State->find('first', array(
                    'conditions' => array(
                        'State.Name' => $_geo[1]
                    ) ,
                    'fields' => array(
                        'State.id'
                    ) ,
                    'recursive' => -1
                ));
                if (empty($state)) {
                    $this->data['State']['name'] = $_geo[1];
                    $this->Ip->State->create();
                    $this->Ip->State->save($this->data['State']);
                    $this->data['Ip']['state_id'] = $this->Ip->State->getLastInsertId();
                } else {
                    $this->data['Ip']['state_id'] = $state['State']['id'];
                }
                $city = $this->Ip->City->find('first', array(
                    'conditions' => array(
                        'City.Name' => $_geo[2]
                    ) ,
                    'fields' => array(
                        'City.id'
                    ) ,
                    'recursive' => -1
                ));
                if (empty($city)) {
                    $this->data['City']['name'] = $_geo[2];
                    $this->Ip->City->create();
                    $this->Ip->City->save($this->data['City']);
                    $this->data['Ip']['city_id'] = $this->Ip->City->getLastInsertId();
                } else {
                    $this->data['Ip']['city_id'] = $city['City']['id'];
                }
                $this->data['Ip']['latitude'] = $_geo[3];
                $this->data['Ip']['longitude'] = $_geo[4];
            }
			
            $this->Ip->create();
            $this->Ip->save($this->data['Ip']);
            return $this->Ip->getLastInsertId();
        } else {
            return $ip['Ip']['id'];
        }
    }
    function findOrSaveAndGetId($data)
    {
        $findExist = $this->find('first', array(
            'conditions' => array(
                'name' => $data
            ) ,
            'fields' => array(
                'id'
            ) ,
            'recursive' => -1
        ));
        if (!empty($findExist)) {
            return $findExist[$this->name]['id'];
        } else {
            $this->data[$this->name]['name'] = $data;
            $this->save($this->data[$this->name]);
            return $this->id;
        }
    }
    function findOrSaveAndGetIdWithArray($name, $data)
    {
        $findExist = $this->find('first', array(
            'conditions' => array(
                'name' => $name
            ) ,
            'fields' => array(
                'id'
            ) ,
            'recursive' => -1
        ));
        if (!empty($findExist)) {
            return $findExist[$this->name]['id'];
        } else {
            $this->data[$this->name] = $data;
            $this->save($this->data[$this->name]);
            return $this->id;
        }
    }
    function _isValidCaptcha()
    {
        include_once VENDORS . DS . 'securimage' . DS . 'securimage.php';
        $img = new Securimage();
        return $img->check($this->data[$this->name]['captcha']);
    }
    function changeFromEmail($from_address = null)
    {
        if (!empty($from_address)) {
            if (preg_match('|<(.*)>|', $from_address, $matches)) {
                return $matches[1];
            } else {
                return $from_address;
            }
        }
    }
	 function getGatewayTypes($field = null) 
    {
        App::import('Model', 'PaymentGateway');
        $this->PaymentGateway = new PaymentGateway();
        $paymentGateways = $this->PaymentGateway->find('all', array(
            'conditions' => array(
                'PaymentGateway.is_active' => 1
            ) ,
            'contain' => array(
                'PaymentGatewaySetting' => array(
                    'conditions' => array(
                        'PaymentGatewaySetting.key' => $field,
                        'PaymentGatewaySetting.test_mode_value' => 1
                    ) ,
                ) ,
            ) ,
            'order' => array(
                'PaymentGateway.display_name' => 'asc'
            ) ,
            'recursive' => 1
        ));
		$payment_gateway_types = array();
		foreach($paymentGateways as $paymentGateway) {
            if (!empty($paymentGateway['PaymentGatewaySetting'])) {
				$payment_gateway_types[$paymentGateway['PaymentGateway']['id']] = $paymentGateway['PaymentGateway']['display_name'];
            }
        }
        return $payment_gateway_types;
    }
    function _getPermissionPerference($user_id)
    {
        App::import('Model', 'UserPermissionPreference');
        $this->UserPermissionPreference = new UserPermissionPreference();
        $get_permission_field = $this->UserPermissionPreference->find('first', array(
            'conditions' => array(
                'UserPermissionPreference.user_id = ' => $user_id,
            ) ,
            'recursive' => -1
        ));
        return $get_permission_field;
    }
    function _sendAlertOnNewMessage($email, $message, $message_id, $template)
    {
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Model', 'Message');
        $this->Message = new Message();
        App::import('Model', 'MessageContent');
        $this->MessageContent = new MessageContent();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        $template = $this->EmailTemplate->selectTemplate($template);
        $get_message_hash = $this->Message->find('first', array(
            'conditions' => array(
                'Message.message_content_id = ' => $message_id,
                'Message.is_sender' => 0
            ) ,
            'fields' => array(
                'Message.id',
                'Message.created',
                'Message.user_id',
                'Message.other_user_id',
                'Message.parent_message_id',
                'Message.message_content_id',
                'Message.message_folder_id',
                'Message.is_sender',
                'Message.is_starred',
                'Message.is_read',
                'Message.is_deleted',
                'Message.hash',
            ) ,
            'contain' => array(
                'MessageContent' => array(
                    'fields' => array(
                        'MessageContent.id',
                        'MessageContent.message',
                        'MessageContent.is_system_flagged',
                        'MessageContent.detected_suspicious_words',
                    )
                )
            ) ,
            'recursive' => 2
        ));
        if (!empty($get_message_hash) && empty($get_message_hash['MessageContent']['is_system_flagged'])) {
            $get_user = $this->Message->User->find('first', array(
                'conditions' => array(
                    'User.id' => $get_message_hash['Message']['user_id']
                ) ,
                'recursive' => -1
            ));
            $emailFindReplace = array(
                '##MESSAGE##' => $message['message'],
                '##SITE_NAME##' => Configure::read('site.name') ,
                '##SITE_URL##' => Router::url('/', true) ,
                '##REPLY_LINK##' => Router::url(array(
                    'controller' => 'messages',
                    'action' => 'compose',
                    'admin' => false,
                    $get_message_hash['Message']['id'],
                    'reply'
                ) , true) ,
                '##VIEW_LINK##' => Router::url(array(
                    'controller' => 'messages',
                    'action' => 'v',
                    'admin' => false,
                    $get_message_hash['Message']['id'],
                ) , true) ,
                '##TO_USER##' => $get_user['User']['username'],
                '##FROM_USER##' => (($template == 'Fund Alert Mail') ? 'Administrator' : $_SESSION['Auth']['User']['username']) ,
                '##SITE_NAME##' => Configure::read('site.name') ,
                '##FROM_USER##' => (($template == 'Fund Alert Mail') ? 'Administrator' : $_SESSION['Auth']['User']['username']) ,
                '##SUBJECT##' => $message['subject'],
            );
            $subject = strtr($template['subject'], $emailFindReplace);
            $content = strtr($template['email_content'], $emailFindReplace);
            // Send e-mail to users
            $this->Email->from = ($template['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $template['from'];
            $this->Email->replyTo = (!empty($template['from']) && $template['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('site.reply_to_email') : $template['reply_to'];
            $this->Email->to = $email;
            $this->Email->subject = $subject;
            $this->Email->send($content);
        }
    }
    function siteCurrencyFormat($amount)
    {
        if (Configure::read('site.currency_symbol_place') == 'left') {
            return Configure::read('site.currency') . $amount;
        } else {
            return $amount . Configure::read('site.currency');
        }
    }
    function _sendAlertOnProjectStatus($project, $emailType, $projectFund = '', $to = '', $paypal_or_wallet = '')
    {
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        $email_message = $this->EmailTemplate->selectTemplate($emailType);
        if (!empty($to) && $to == 'admin') {
            $username = 'admin';
        } else {
            $username = (!empty($to) && $to == 'buyer') ? $projectFund['User']['username'] : $project['User']['username'];
        }
        $amount = (!empty($projectFund['ProjectFund']['amount'])) ? $projectFund['ProjectFund']['amount'] : $project['ProjectFund']['amount'];
        $emailFindReplace = array(
            '##USERNAME##' => $username,
            '##PROJECT_NAME##' => $project['Project']['name'],
            '##PROJECT_LINK##' => Router::url(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug'],
                'admin' => false
            ) , true) ,
            '##BUYER_USERNAME##' => !empty($_SESSION['Auth']['User']['username'])?$_SESSION['Auth']['User']['username']:'',
            '##AMOUNT##' => Configure::read('site.currency') . $amount,
            '##SITE_NAME##' => Configure::read('site.name') ,
            '##SITE_URL##' => Router::url('/', true) ,
            '##PAYPAL_OR_WALLET##' => $paypal_or_wallet,
        );
        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
        $subjectTag = '';
        if (!empty($to) && $to == 'admin') {
            $this->Email->to = Configure::read('EmailTemplate.admin_email');
            $subjectTag = '[' . Configure::read('site.name') . ']';
        } else if (!empty($to) && $to == 'buyer') {
            $this->Email->to = $projectFund['User']['email'];
        } else {
            $this->Email->to = $project['User']['email'];
        }
        $this->Email->subject = $subjectTag . strtr($email_message['subject'], $emailFindReplace);
        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
    }
    function _sendAlertOnProjectSuccessful($to_users, $project, $projectUserType, $user_lists = array())
    {
        App::import('Model', 'User');
        $this->User = new User();
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        if (!empty($to_users)) {
            $users = $this->User->find('all', array(
                'conditions' => array(
                    'User.id' => $to_users
                ) ,
                'fields' => array(
                    'User.id',
                    'User.email',
                    'User.username',
                ) ,
                'recursive' => -1
            ));
            foreach($users as $user) {
                if (!in_array($user['User']['id'], $user_lists)) {
                    $user_preference = $this->_getPermissionPerference($user['User']['id']);
                    if (($projectUserType == ConstProjectUsers::Backer && $user_preference['UserPermissionPreference']['project_successfull_mail_send_backer'] == 1) || ($projectUserType == ConstProjectUsers::Follower && $user_preference['UserPermissionPreference']['project_successfull_mail_send_follower'] == 1) || ($projectUserType == ConstProjectUsers::Owner && $user_preference['UserPermissionPreference']['project_successfull_mail_send_owner'] == 1)) {
                        $email_message = $this->EmailTemplate->selectTemplate('Project Successful Alert');
                        $emailFindReplace = array(
                            '##FROM_EMAIL##' => ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'],
                            '##USERNAME##' => $user['User']['username'],
                            '##USER##' => $_SESSION['Auth']['User']['username'],
                            '##SITE_NAME##' => Configure::read('site.name') ,
                            '##PROJECT_NAME##' => $project['Project']['name'],
                            '##PROJECT_LINK##' => Router::url(array(
                                'controller' => 'projects',
                                'action' => 'view',
                                $project['Project']['slug'],
                                'admin' => false
                            ) , true) ,
                            '##SITE_URL##' => Router::url('/', true) ,
                        );
                        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
                        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
                        $this->Email->to = $user['User']['email'];
                        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
                        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
                        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
                    }
                    $user_lists[] = $user['User']['id'];
                }
            }
        }
        return $user_lists;
    }
    function _sendAlertOnProjectExpired($to_users, $project, $projectUserType, $user_lists = array())
    {
        App::import('Model', 'User');
        $this->User = new User();
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        if (!empty($to_users)) {
            $users = $this->User->find('all', array(
                'conditions' => array(
                    'User.id' => $to_users
                ) ,
                'fields' => array(
                    'User.id',
                    'User.email',
                    'User.username',
                ) ,
                'recursive' => -1
            ));
            foreach($users as $user) {
                if (!in_array($user['User']['id'], $user_lists)) {
                    $user_preference = $this->_getPermissionPerference($user['User']['id']);
                    if (($projectUserType == ConstProjectUsers::Backer && $user_preference['UserPermissionPreference']['project_expired_mail_send_backer'] == 1) || ($projectUserType == ConstProjectUsers::Follower && $user_preference['UserPermissionPreference']['project_expired_mail_send_follower'] == 1) || ($projectUserType == ConstProjectUsers::Owner && $user_preference['UserPermissionPreference']['project_expired_mail_send_owner'] == 1)) {
                        $email_message = $this->EmailTemplate->selectTemplate('Project Expired Alert');
                        $emailFindReplace = array(
                            '##FROM_EMAIL##' => ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'],
                            '##USERNAME##' => $user['User']['username'],
                            '##USER##' => !empty($_SESSION['Auth']['User']['username'])?!empty($_SESSION['Auth']['User']['username']):'',
                            '##SITE_NAME##' => Configure::read('site.name') ,
                            '##PROJECT_NAME##' => $project['Project']['name'],
                            '##PROJECT_LINK##' => Router::url(array(
                                'controller' => 'projects',
                                'action' => 'view',
                                $project['Project']['slug'],
                                'admin' => false
                            ) , true) ,
                            '##SITE_URL##' => Router::url('/', true) ,
                        );
                        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
                        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
                        $this->Email->to = $user['User']['email'];
                        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
                        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
                        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
                    }
                    $user_lists[] = $user['User']['id'];
                }
            }
        }
        return $user_lists;
    }
    function _sendAlertOnProjectGoalReached($to_users, $project, $projectUserType, $user_lists = array())
    {
        App::import('Model', 'User');
        $this->User = new User();
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        if (!empty($to_users)) {
            $users = $this->User->find('all', array(
                'conditions' => array(
                    'User.id' => $to_users
                ) ,
                'fields' => array(
                    'User.id',
                    'User.email',
                    'User.username',
                ) ,
                'recursive' => -1
            ));
            foreach($users as $user) {
                if (!in_array($user['User']['id'], $user_lists)) {
                    $user_preference = $this->_getPermissionPerference($user['User']['id']);
                    if (($projectUserType == ConstProjectUsers::Backer && $user_preference['UserPermissionPreference']['project_goalreached_mail_send_backer'] == 1) || ($projectUserType == ConstProjectUsers::Follower && $user_preference['UserPermissionPreference']['project_goalreached_mail_send_follower'] == 1) || ($projectUserType == ConstProjectUsers::Owner && $user_preference['UserPermissionPreference']['project_goalreached_mail_send_owner'] == 1)) {
                        $email_message = $this->EmailTemplate->selectTemplate('Project Goal Reached Alert');
                        $emailFindReplace = array(
                            '##FROM_EMAIL##' => ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'],
                            '##USERNAME##' => $user['User']['username'],
                            '##USER##' => $_SESSION['Auth']['User']['username'],
                            '##SITE_NAME##' => Configure::read('site.name') ,
                            '##PROJECT_NAME##' => $project['Project']['name'],
                            '##PROJECT_LINK##' => Router::url(array(
                                'controller' => 'projects',
                                'action' => 'view',
                                $project['Project']['slug'],
                                'admin' => false
                            ) , true) ,
                            '##SITE_URL##' => Router::url('/', true) ,
                        );
                        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
                        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
                        $this->Email->to = $user['User']['email'];
                        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
                        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
                        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
                    }
                    $user_lists[] = $user['User']['id'];
                }
            }
        }
        return $user_lists;
    }
    function _sendAlertOnProjectCancelled($to_users, $project, $projectUserType, $user_lists = array())
    {
        App::import('Model', 'User');
        $this->User = new User();
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        if (!empty($to_users)) {
            $users = $this->User->find('all', array(
                'conditions' => array(
                    'User.id' => $to_users
                ) ,
                'fields' => array(
                    'User.id',
                    'User.email',
                    'User.username',
                ) ,
                'recursive' => -1
            ));
            foreach($users as $user) {
                if (!in_array($user['User']['id'], $user_lists)) {
                    $user_preference = $this->_getPermissionPerference($user['User']['id']);
                    if (($projectUserType == ConstProjectUsers::Backer && $user_preference['UserPermissionPreference']['project_cancel_mail_send_backer'] == 1) || ($projectUserType == ConstProjectUsers::Follower && $user_preference['UserPermissionPreference']['project_cancel_mail_send_follower'] == 1) || ($projectUserType == ConstProjectUsers::Owner && $user_preference['UserPermissionPreference']['project_cancel_mail_send_owner'] == 1)) {
                        $email_message = $this->EmailTemplate->selectTemplate('Project Cancelled Alert');
                        $emailFindReplace = array(
                            '##FROM_EMAIL##' => ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'],
                            '##USERNAME##' => $user['User']['username'],
                            '##USER##' => $_SESSION['Auth']['User']['username'],
                            '##SITE_NAME##' => Configure::read('site.name') ,
                            '##PROJECT_NAME##' => $project['Project']['name'],
                            '##PROJECT_LINK##' => Router::url(array(
                                'controller' => 'projects',
                                'action' => 'view',
                                $project['Project']['slug'],
                                'admin' => false
                            ) , true) ,
                            '##SITE_URL##' => Router::url('/', true) ,
                        );
                        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
                        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
                        $this->Email->to = $user['User']['email'];
                        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
                        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
                        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
                    }
                    $user_lists[] = $user['User']['id'];
                }
            }
        }
        return $user_lists;
    }
    function _sendAlertOnProjectAdd($project, $emailType)
    {
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        $email_message = $this->EmailTemplate->selectTemplate($emailType);
        $emailFindReplace = array(
            '##USERNAME##' => $project['User']['username'],
            '##PROJECT_NAME##' => $project['Project']['name'],
            '##PROJECT_URL##' => Router::url(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug'],
                'admin' => false
            ) , true) ,
            '##CATEGORY##' => $project['ProjectCategory']['name'],
            '##SITE_NAME##' => Configure::read('site.name') ,
            '##SITE_URL##' => Router::url('/', true) ,
            '##AMOUNT##' => $project['Project']['needed_amount'],
        );
        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
        $this->Email->to = Configure::read('EmailTemplate.admin_email');
        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
    }
    function _sendAlertOnProjectStatusToAdmin($project, $old_status, $current_status)
    {
        App::import('Model', 'ProjectStatus');
        $this->ProjectStatus = new ProjectStatus();
        $projectStatus = $this->ProjectStatus->find('list');
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        $email_message = $this->EmailTemplate->selectTemplate('Admin Project Status Alert');
        $emailFindReplace = array(
            '##PROJECT_NAME##' => $project['Project']['name'],
            '##PROJECT_URL##' => Router::url(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug'],
                'admin' => false
            ) , true) ,
            '##OLD_STATUS##' => $projectStatus[$old_status],
            '##SITE_NAME##' => Configure::read('site.name') ,
            '##SITE_URL##' => Router::url('/', true) ,
            '##NEW_STATUS##' => $projectStatus[$current_status],
        );
        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
        $this->Email->to = Configure::read('EmailTemplate.admin_email');
        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
    }
	function _sendAlertOnProjectReserveAmountReached($to_users, $project, $projectUserType, $user_lists = array())
    {
        App::import('Model', 'User');
        $this->User = new User();
        App::import('Model', 'EmailTemplate');
        $this->EmailTemplate = new EmailTemplate();
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Email');
		$this->Email = new EmailComponent($collection);
        if (!empty($to_users)) {
            $users = $this->User->find('all', array(
                'conditions' => array(
                    'User.id' => $to_users
                ) ,
                'fields' => array(
                    'User.id',
                    'User.email',
                    'User.username',
                ) ,
                'recursive' => -1
            ));
            foreach($users as $user) {
                if (!in_array($user['User']['id'], $user_lists)) {
                    $user_preference = $this->_getPermissionPerference($user['User']['id']);
                    if (($projectUserType == ConstProjectUsers::Backer && $user_preference['UserPermissionPreference']['project_reserveamountreached_mail_send_backer'] == 1) || ($projectUserType == ConstProjectUsers::Follower && $user_preference['UserPermissionPreference']['project_reserveamountreached_mail_send_follower'] == 1) || ($projectUserType == ConstProjectUsers::Owner && $user_preference['UserPermissionPreference']['project_reserveamountreached_mail_send_owner'] == 1)) {
                        $email_message = $this->EmailTemplate->selectTemplate('Project Reserve Amount Reached Alert');
                        $emailFindReplace = array(
                            '##FROM_EMAIL##' => ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'],
                            '##USERNAME##' => $user['User']['username'],
                            '##USER##' => $_SESSION['Auth']['User']['username'],
                            '##SITE_NAME##' => Configure::read('site.name') ,
                            '##PROJECT_NAME##' => $project['Project']['name'],
                            '##PROJECT_LINK##' => Router::url(array(
                                'controller' => 'projects',
                                'action' => 'view',
                                $project['Project']['slug'],
                                'admin' => false
                            ) , true) ,
                            '##SITE_URL##' => Router::url('/', true) ,
                        );
                        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
                        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
                        $this->Email->to = $user['User']['email'];
                        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
                        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
                        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
                    }
                    $user_lists[] = $user['User']['id'];
                }
            }
        }
        return $user_lists;
    }
    function findCountryId($data) 
    {
        $findExist = $this->find('first', array(
            'conditions' => array(
                'iso2' => $data
            ) ,
            'fields' => array(
                'id'
            ) ,
            'recursive' => -1
        ));
        return $findExist[$this->name]['id'];
    }
    function _uuid()
    {
        return sprintf('%07x%1x', mt_rand(0, 0xffff) , mt_rand(0, 0x000f));
    }
    function _unum()
    {
        $acceptedChars = '0123456789';
        $max = strlen($acceptedChars) -1;
        $unique_code = '';
        for ($i = 0; $i < 8; $i++) {
            $unique_code.= $acceptedChars{mt_rand(0, $max) };
        }
        return $unique_code;
    }
}
?>